﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using eLuk.CommandEngine;
using eLuk.Entity;
namespace eLuk.Runtime
{
	public class IMAPConnectedState : IMAPState, IAuthorizable, IDisconnectable
	{
		public IMAPConnectedState()
		{
		}
		public override void Change( IMAPSession session )
		{
			session.CurrentState = new IMAPAuthenticatedState();
		}
		public string Capability( IMAPSession session )
		{
			return "";
		}
		public async Task Login( IMAPSession session )
		{
			try
			{
				IMAPCommand login = new IMAPCommand( "LOGIN", "LOGIN \"{0}\" \"{1}\"" );
				string commandResult = await session.Engine.ExecuteAsync( login, session.Engine.Channel.Server.Credential.User, session.Engine.Channel.Server.Credential.Password );
				bool success = await this.UpdateCapability( session, commandResult );
				if ( success )
					session.CurrentState = new IMAPAuthenticatedState();
				else
					session.CurrentState = new IMAPAuthenticationFailedState();
				//this.Change( session );
			}
			catch ( Exception ex )
			{
			}
		}
		internal async Task<bool> UpdateCapability( IMAPSession session, string capabilities )
		{
			bool result = false;
			try
			{
				if ( session.Engine.Channel.Server.Capability != null )
				{
					session.Engine.Channel.Server.Capability = null;
				}
				session.Engine.Channel.Server.Capability = new IMAPCapability( capabilities );
				await Task.Run( () =>
					{
						result = true & capabilities.StartsWith( "* CAPABILITY" ) || capabilities.Contains( "* CAPABILITY" );
					}
				);
			}
			catch ( Exception ex )
			{
				result = false;
			}
			return result;
		}
		public string Noop( IMAPSession session )
		{
			return "";
		}
		public string StartTTLs( IMAPSession session )
		{
			return "";
		}
		public string Disconnect( IMAPSession session )
		{
			return "";
		}
	}
}